<?php
class Setting {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = null;
	/**
	* @var string Database table to be used
	*/
	var $table = null;
	/**
	* @var mixed Options
	*/
	var $opts = null;
	/**
	* @var array Coeditor table
	*/
	var $coed = null;
	/**
	* @var array Taxonomic positions
	*/
	var $ranks = null;
	
	/**
	* Setting constructor
	* Initializes setting variables for intended request
	* 
	* @param string $area Area of concentration
	* @param mixed $opts Additional options
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $opts, $mysqli, $user) {
		# Include all necessary classes
		require_once "class/account.php";
		require_once "class/editor.php";
		require_once "class/setting.php";
		require_once "class/fpdf.php";
		require_once "class/file.php";
		require_once "class/resource.php";
		require_once "class/location.php";
		require_once "class/microorganism.php";
		require_once "class/image.php";
		require_once "class/document.php";
		require_once "class/section.php";
		require_once "class/project.php";
		require_once "class/tool.php";
		
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		
		switch($area) {
			# Microorganisms
			case "micro":
				$this->table = "Microorganisms";
				$this->coed = "MicroCoeds";
			break;
			
			# Taxonomy
			case "taxon":
				$this->ranks = array('Kingdoms', 'Phyla', 'Classes', 'Orders', 'Families', 'Genera', 'Species');
				$this->table = $ranks[$opts['rank']];
			break;
			
			# Projects
			case "proj":
				$this->table = "Projects";
				$this->coed = "ProjCoeds";
			break;
			
			# Images
			case "img":
				$this->table = "Images";
				$this->coed = "ImgCoeds";
			break;
			
			# Documents
			case "doc":
				$this->table = "Documents";
				$this->coed = "DocCoeds";
			break;
			
			# Locations
			case "loc":
				$this->table = "Locations";
				$this->coed = "LocCoeds";
			break;
			
			# Resources
			case "rsrc":
				$this->table = "Resources";
				$this->coed = "RsrcCoeds";
			break;
			
			# Accounts
			case "acct":
				$this->table = "Accounts";
				$this->coed = "Editors";
			break;
			
			# Editors
			case "edtr":
				$this->table = "Editors";
				$this->coed = "Editors";
			break;
		}
	}
	
	/**
	* Search item
	* Searches for the item based on its ID
	* 
	* @access public
	* @param string $id ID of area/item
	* 
	* @return array Editors, Item resource, Settings
	*/
	public function search($id) {
		$arrEdtrID = array();
		
		# Search for settings of an item
		$sel = ($this->area!="edtr" and $this->area!='taxon')
			? "SELECT Categ, Visib, CrtBy FROM {$this->table} WHERE ID='{$id}' LIMIT 0, 1"
			: "SELECT CrtBy FROM {$this->table} WHERE ID='{$id}' LIMIT 0, 1";
		
		$res = $this->mysqli->query($sel);
		
		# Item found
		if($res and !empty($res->num_rows)) {
			# Assign settings
			$obj = $res->fetch_object();
			$categ = isset($obj->Categ) ? $obj->Categ : null; # Category
			$visib = isset($obj->Visib) ? $obj->Visib : null; # Visibility
			$arrEdtrID[] = $obj->CrtBy; # Author
			$author = $obj->CrtBy;
		}
		# Item not found
		else {
			$author = null;
			$categ = null;
			$visib = null;
		}
		
		# Search accounts bering author ID
		$sel = "
			SELECT T1.* FROM Accounts AS T1 INNER JOIN {$this->coed} AS T2
				ON T1.ID=T2.CID WHERE T2.PID='{$id}' OR T1.ID='{$author}'
		";
		
		# Include account IDs to list
		if($res = $this->mysqli->query($sel)) {
			while($coed = $res->fetch_object()) {
				$arrEdtrID[] = $coed->ID;
			}
		}
		
		return array($arrEdtrID, $res, array($categ, $visib));
	}
	
	/**
	* Manage item
	* Verifies if item is permitted to be managed by current user
	* Show controls to manage item
	* 
	* @access public
	* @param string $id ID of area/item
	* 
	* @return boolean True on success, false on error
	*/
	public function allow($id) {
		# Search for editors of that item
		list($arrEdtrID, $res, $cv) = $this->search($id);
		
		# If current user is included in the list of editors, continue
		if(in_array($this->user['id'], $arrEdtrID) or in_array($this->user['type'], array('ADMIN','PRIME'))) {
			# User is an editor
			if($this->area!="edtr") {
				# Category and visibility of the item ?>
				<label>Category:</label>
				<select name="categ" class="safe reqd">
					<option value="ADV" <?php if($cv[0]=="ADV") echo 'selected="selected"' ?>>Advanced</option>
					<option value="BSC" <?php if($cv[0]=="BSC") echo 'selected="selected"' ?>>Basic</option>
				</select> &nbsp; &nbsp; &nbsp;
				
				<label>Visibility:</label>
				<select name="visib" class="safe reqd">
					<option value="PRV" <?php if($cv[1]=="PRV") echo 'selected="selected"' ?>>Private</option>
					<option value="PUB" <?php if($cv[1]=="PUB") echo 'selected="selected"' ?>>Public</option>
				</select><br/> <?php
			} ?>
			
			<label>Coeditors:</label> <?php
			# List all coeditors of the item
			if(($size = $res->num_rows) > 0) {
				$res->data_seek(0);	$i = 1; echo "({$size})<br/>"; ?>
				
				<ol> <?php
					while($coed = $res->fetch_object()) { ?>
						<li class="coed">
							<a name="coed" href="main.php?acct=view&id=<?php echo $coed->ID ?>" class="coed">
								<?php echo $coed->Lname.", ".$coed->Fname.", ".substr($coed->Mname, 0, 1)."." ?></a>
							<button type="button" class="remove icon" data-area="coed" data-id="<?php echo $coed->ID ?>"></button>
						</li> <?php
					} ?>
				</ol> <?php
			}
			else {
				echo 'No co-editors found.<br/>';
			} ?>
			
			<div class="none">
				<div class="default">
					<input name="coed[val][]" type="text" class="coed" placeholder="Account name or Email" data-guess="acct=guess"/>
					<button class="append icon" type="button" data-area="coed" data-id="0"></button>
					<input type="hidden" name="coed[id][]" class="abled"/>
				</div>
				<div class="coeds"></div>
			</div>
			<button type="button" class="addmore peel on prev" data-on="Add" data-off="Cancel">Add</button> <?php
			
			return true;
		}
		# User is not allowed
		else {
			return false;
		}
	}
	
	/**
	* Check permission
	* Verifies if item is permitted to be managed by current user
	* 
	* @access public
	* @param string $id ID of area/item
	* 
	* @return boolean True on success, false on error
	*/
	public function verify($id) {
		# Search editors of item
		list($arrEdtrID, $res, $cv) = $this->search($id);
		
		# User is included on the list of editors
		if(in_array($this->user['id'], $arrEdtrID) or in_array($this->user['type'], array('ADMIN','PRIME'))) {
			return true;
		}
		
		# User is not on the list
		return false;
	}
	
	/**
	* Describe item
	* Describe an item's entry to the system
	* 
	* @access public
	* @param string $id ID of area/item
	* 
	* @return boolean True on success, false on error
	*/
	public function describe($id) {
		switch($this->area) {
			case 'micro':
				$sel = "
					SELECT T1.Name as Name, T1.Categ, T1.Visib, T1.CoedNo, T1.UpdBy, T1.UpdOn, T1.UpdNo, T1.ShrBy, T1.ShrOn, T1.ShrNo, T1.CrtBy, T1.CrtOn, T1.Remove
						FROM Microorganisms AS T1 INNER JOIN Accounts AS T2 ON T2.ID IN (T1.UpdBy, T1.ShrBy, T1.CrtBy)
					WHERE T1.ID='$id'
				";
			break;
			
			case 'img':
				$sel = "
					SELECT T1.Title as Name, T1.Categ, T1.Visib, T1.CoedNo, T1.UpdBy, T1.UpdOn, T1.UpdNo, T1.ShrBy, T1.ShrOn, T1.ShrNo, T1.CrtBy, T1.CrtOn, T1.Remove
						FROM Images AS T1 INNER JOIN Accounts AS T2 ON T2.ID IN (T1.UpdBy, T1.ShrBy, T1.CrtBy)
					WHERE T1.ID='$id'
				";
			break;
			
			case 'doc':
				$sel = "
					SELECT T1.Title as Name, T1.Categ, T1.Visib, T1.CoedNo, T1.UpdBy, T1.UpdOn, T1.UpdNo, T1.ShrBy, T1.ShrOn, T1.ShrNo, T1.CrtBy, T1.CrtOn, T1.Remove
						FROM Documents AS T1 INNER JOIN Accounts AS T2 ON T2.ID IN (T1.UpdBy, T1.ShrBy, T1.CrtBy)
					WHERE T1.ID='$id'
				";
			break;
			
			case 'loc':
				$sel = "
					SELECT T1.Name as Name, T1.Categ, T1.Visib, T1.CoedNo, T1.UpdBy, T1.UpdOn, T1.UpdNo, T1.ShrBy, T1.ShrOn, T1.ShrNo, T1.CrtBy, T1.CrtOn, T1.Remove
						FROM Locations AS T1 INNER JOIN Accounts AS T2 ON T2.ID IN (T1.UpdBy, T1.ShrBy, T1.CrtBy)
					WHERE T1.ID='$id'
				";
			break;
			
			case 'rsrc':
				$sel = "
					SELECT T1.Title as Name, T1.Categ, T1.Visib, T1.CoedNo, T1.UpdBy, T1.UpdOn, T1.UpdNo, T1.CrtBy, T1.CrtOn, T1.Remove
						FROM Resources AS T1 INNER JOIN Accounts AS T2 ON T2.ID IN (T1.UpdBy, T1.CrtBy)
					WHERE T1.ID='$id'
				";
			break;
			
			case 'proj':
				$sel = "
					SELECT T1.Title as Name, T1.Categ, T1.Visib, T1.CoedNo, T1.UpdBy, T1.UpdOn, T1.UpdNo, T1.ShrBy, T1.ShrOn, T1.ShrNo, T1.CrtBy, T1.CrtOn, T1.Remove
						FROM Projects AS T1 INNER JOIN Accounts AS T2 ON T2.ID IN (T1.UpdBy, T1.ShrBy, T1.CrtBy)
					WHERE T1.ID='$id'
				";
			break;
			
			case 'acct':
				$sel = "
					SELECT SgnOn, UpdBy, UpdOn, UpdNo, CrtBy, CrtOn, Remove FROM Accounts WHERE ID='$id'
				";
			break;
			
			case 'edtr':
				$sel = "
					SELECT UpdBy, UpdOn, UpdNo, CrtBy, CrtOn, Remove FROM Editors WHERE ID='$id'
				";
			break;
			
			case 'appn':
				$sel = "
					SELECT CrtOn FROM Applications WHERE ID='$id'
				";
			break;
		}
		
		if(!($res = $this->mysqli->query($sel))) {
			return false;
		}
		
		$obj = $res->fetch_object();
		
		$this->getItemStatus($obj, $id);
		$this->getCategVisib($obj->Categ, $obj->Visib);
		$this->getCreator($obj->CrtBy, $obj->CrtOn);
		$this->getUpdater($obj->UpdNo, $obj->UpdBy, $obj->UpdOn);
		if($this->area!='rsrc') { $this->getSharer($obj->ShrNo, $obj->ShrBy, $obj->ShrOn); }
		$this->getCoeditors($id);
		
		return true;
	}
	
	/**
	* Find account
	* Search account associated to the item
	* 
	* @access public
	* @param string $id ID of area/item
	* 
	* @return mixed True on success, false on error
	*/
	public function findAcct($id) {
		$sel = "SELECT * FROM Accounts WHERE ID='$id'";
		
		if($res = $this->mysqli->query($sel)) {
			return $res->fetch_object();
		}
		
		return null;
	}
	
	/**
	* Get item status
	* Checks whether the item is active or removed
	* 
	* @access public
	* @param mixed $obj Resource of area/item
	* @param string $id ID of area/item
	*/
	private function getItemStatus($obj, $id) { ?>
		<div><label><a href="main.php?<?php echo $this->area ?>=view&id=<?php echo $id ?>" target="_blank"><?php echo $obj->Name ?></a></label></div><hr/>
		<label>Status:</label> <?php echo (isset($status) and $status=='0')
			? '<span data-tool="{\'head\':\'Can be managed by authorized users\',\'x\':\'l\'}">Active</span>'
			: '<span data-tool="{\'head\':\'Excluded from being managed<br/>by users except admins\',\'x\':\'l\'}">Removed</span>'; ?> &nbsp; &nbsp; &nbsp; <?php
	}
	
	/**
	* Get item category
	* Shows an item's downloadability
	* 
	* @access public
	* @param string $categ Category of item 
	* 
	* @return array Category and info
	*/
	private function getCateg($categ) {
		return $categ=='ADV'
			? array('Advanced', 'Can be downloaded by authors and coeditors only')
			: array('Basic', 'Can be downloaded by all registered users');
	}
	
	/**
	* Get item visibility
	* Shows an item's visibility to users
	* 
	* @access public
	* @param string $visib Visibility of item 
	* 
	* @return array Visibility and info
	*/
	private function getVisib($visib) {
		return $visib=='PRV'
			? array('Private', 'Can be seen by authors and coeditors only')
			: array('Public', 'Can be seen by all users');
	}
	
	/**
	* Get item category and visibility
	* Shows an item's downloadability and visibility to users
	* 
	* @access public
	* @param string $category Category of item 
	* @param string $visib Visibility of item 
	*/
	private function getCategVisib($categ, $visib) { ?>
		<label>Category:</label> <?php
			list($categ, $help) = $this->getCateg($categ);
			echo '<span data-tool="{\'head\':\''.$help.'\',\'x\':\'l\'}">'.$categ.'</span>'; ?> &nbsp; &nbsp; &nbsp;
		<label>Visibility:</label> <?php
			list($visib, $help) = $this->getVisib($visib);
			echo '<span data-tool="{\'head\':\''.$help.'\',\'x\':\'l\'}">'.$visib.'</span>'; ?><br/> <?php
	}
	
	/**
	* Get updates
	* Shows an item's update details
	* 
	* @access public
	* @param int $updno Update count 
	* @param string $updby Last updater 
	* @param string $updon Date of update 
	*/
	private function getUpdater($updno, $updby, $updon) { ?>
		<label>Total updates:</label> <?php
			echo $updno; ?><br/>
		<label>Last update by: <?php
			if(empty($updby)) {
				echo "</label> no one";
			}
			else {
				$updby = $this->findAcct($updby); ?>
				</label>
					<a href="main.php?edtr=view&id=<?php echo $updby->EID ?>" target="_blank" data-tool="{'head':'<?php echo $updby->Email ?>','stay':1,'x':'l'}"><?php
						echo $updby->Lname.', '.$updby->Fname.', '.substr($updby->Mname, 0, 1).'.'; ?></a>
				<label>on</label> <?php
					$this->formatDate($updon);
			} ?>
		<br/> <?php
	}
	
	/**
	* Get shares
	* Shows an item's share details
	* 
	* @access public
	* @param int $shrno Share count 
	* @param string $shrby Last sharer 
	* @param string $shron Date of share 
	*/
	private function getSharer($shrno, $shrby, $shron) { ?>
		<label>Total shares:</label> <?php
			echo $shrno; ?><br/>
		<label>Last share by: <?php
			if(empty($shrby)) {
				echo "</label> no one";
			}
			else {
				$shrby = $this->findAcct($shrby); ?>
				</label>
					<a href="main.php?edtr=view&id=<?php echo $shrby->EID ?>" target="_blank" data-tool="{'head':'<?php echo $shrby->Email ?>','stay':1,'x':'l'}"><?php
						echo $shrby->Lname.', '.$shrby->Fname.', '.substr($shrby->Mname, 0, 1).'.'; ?>
				<label>on</label> <?php
					$this->formatDate($shron);
			}
	}
	
	/**
	* Get creator
	* Shows an item's author/creator
	* 
	* @access public
	* @param string $crtby Creator 
	* @param string $crton Date of creation 
	*/
	private function getCreator($crtby, $crton) {
		$crtby = $this->findAcct($crtby); ?>
		<label>Created by:</label>
			<a href="main.php?edtr=view&id=<?php echo $crtby->EID ?>" target="_blank" data-tool="{'head':'<?php echo $crtby->Email ?>','stay':1,'x':'l'}"> <?php
				echo $crtby->Lname.', '.$crtby->Fname.', '.substr($crtby->Mname, 0, 1).'.'; ?></a>
		<label>on</label> <?php echo
			$this->formatDate($crton); ?>
		<hr/> <?php
	}
	
	/**
	* Format date
	* Shows an date of an item
	* 
	* @access public
	* @param string $date date 
	*/
	private function formatDate($date) {
		$date = strtotime($date);
		echo "<span data-tool=\"{'head':'".date('g:i:s A', $date)."'}\">".date('F j, Y', $date).'</span>';
	}
	
	/**
	* Get item's coeditors
	* Get an item's coeditors
	* 
	* @access public
	* @param string $id ID of item 
	*/
	private function getCoeditors($id) {
		switch($this->area) {
			case 'micro':
				$sel = "
					SELECT T1.*, T2.* FROM Accounts AS T1 INNER JOIN MicroCoeds AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn
				";
			break;
			
			case 'img':
				$sel = "
					SELECT T1.*, T2.* FROM Accounts AS T1 INNER JOIN ImgCoeds AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn
				";
			break;
			
			case 'doc':
				$sel = "
					SELECT T1.*, T2.* FROM Accounts AS T1 INNER JOIN DocCoeds AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn
				";
			break;
			
			case 'loc':
				$sel = "
					SELECT T1.*, T2.* FROM Accounts AS T1 INNER JOIN LocCoeds AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn
				";
			break;
			
			case 'rsrc':
				$sel = "
					SELECT T1.*, T2.* FROM Accounts AS T1 INNER JOIN RsrcCoeds AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn
				";
			break;
			
			case 'proj':
				$sel = "
					SELECT T1.*, T2.* FROM Accounts AS T1 INNER JOIN ProjCoeds AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn
				";
			break;
		}
		
		$res = $this->mysqli->query($sel);
		
		if($res) { ?><hr/>
			<label>Co-edited with:</label> <?php
			if(empty($res->num_rows)) {
				echo 'no one';
			}
			else { ?>
				<ol> <?php
					while($obj = $res->fetch_object()) { ?>
						<li><a href="main.php?edtr=view&id=<?php echo $obj->EID ?>" data-tool="{'head':'<?php echo $obj->Email ?>','stay':1,'x':'l'}" target="_blank">
							<?php echo $obj->Lname.', '.$obj->Fname.' '.substr($obj->Mname, 0, 1).'.' ?></a> since <span><?php echo $this->formatDate($obj->CrtOn) ?></span></li> <?php
					} ?>
				</ol> <?php
			}
		}
	}
}




















?>